<?php

namespace App\Models;

use Route;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class AdminUser extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'is_lock', 'avatar', 'phone'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * 关联角色
     */
    public function roles()
    {
        return $this->belongsToMany(AdminRole::class, 'admin_role_users', 'user_id', 'role_id')->where('status', 1);
    }

    /**
     * 关联权限
     */
    public function permissions()
    {
        return $this->belongsToMany(AdminPermission::class, 'admin_permission_users', 'user_id', 'permission_id')->where('status', 1);
    }

    /**
     * 访问权限验证
     *
     * @param $name
     * @return boolean
     */
    public function owns($name = null)
    {
        $temp = [
            'show' => 'view',
            'store' => 'create',
            'edit' => 'update',
            'destroy' => 'delete',
        ];

        // 超级用户
        if ($this->isSuper()){
            return true;
        }

        if (is_null($name)){
            $name = Route::currentRouteName();
        }

        $name = explode('.', $name);
        if (isset($temp[$name[2]])){
            $name[2] = $temp[$name[2]];
        }

        $name = join('.', $name);

        $permissions = $this->myPermissions()->get()->pluck('name')->toArray();
        return in_array($name, $permissions);
    }

    /**
     * 获取用户所有权限 用户权限 + 用户角色权限
     */
    public function myPermissions()
    {
        $permission = new AdminPermission();
        if ($this->isSuper()){
            return $permission;
        }

        // 用户权限
        $myPermissionIds = AdminPermissionUser::where('user_id', $this->id)->pluck('permission_id')->toArray();

        // 用户角色权限
        $rolePermissionIds = $this->roles()->get()->pluck('id');
        if ($rolePermissionIds){
            $rolePermissionIds = AdminPermissionRole::whereIn('role_id', $rolePermissionIds)->pluck('permission_id')->toArray();
            if ($rolePermissionIds){
                $myPermissionIds = array_unique(array_merge($myPermissionIds, $rolePermissionIds));
            }
        }

        if (empty($myPermissionIds)){
            return $permission->where('id', 0);
        }
        return $permission->whereIn('id', $myPermissionIds)->where('status', 1);
    }

    /**
     * 是否已锁定
     * @return mixed
     */
    public function isLock()
    {
        return $this->is_lock;
    }

    /**
     * 是否超级用户
     *
     * @return bool
     */
    public function isSuper(){
        return $this->name === 'root';
    }
}
